package com.example.qxfw.mongodb.qx.controller;

import com.dmgis.entity.*;
import com.dmgis.weblib.GridAnalysis;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.mongodb.qx.dto.GridPointDto;
import com.example.qxfw.mongodb.qx.entity.QxGridFile;
import com.example.qxfw.mongodb.qx.service.QxGridFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Api(tags = "Mongo气象库-省台格点文件")
@RestController
@CrossOrigin
@RequestMapping("/qx/gridFile")
public class GridFileController {

    @Autowired
    private QxGridFileService qxGridFileService;

    @ApiOperation("用id获取")
    @GetMapping("/getById")
    public SysResult getById(String id) throws IOException {
        QxGridFile gridFile = qxGridFileService.getById(id);
        InputStream inputStream = new ByteArrayInputStream(gridFile.getData());
        File file = getFile("grid");
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = inputStream.read(buffer, 0, 1024)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        log.info("文件保存成功，文件路径："+file.getPath()+System.currentTimeMillis());

        GridAnalysis gridAlanly = new GridAnalysis();
        gridAlanly.openFile(file.getPath());
        DmGridInfo gridInfo = gridAlanly.getGridInfo();
        log.info("解析grid完成："+System.currentTimeMillis());

        float[] fvals = new float[gridInfo.getRows()*gridInfo.getCols()];
        for (int i=1; i<=gridInfo.getRows(); i++){
            for (int j=1; j<=gridInfo.getCols(); j++){
                fvals[(i-1)*gridInfo.getRows()+j-1] =  gridAlanly.getValue(i,j);
            }
        }
        log.info("取行列值完成："+System.currentTimeMillis());

        int rows = gridInfo.getRows();
        int cols = gridInfo.getCols();
        double minx = gridInfo.getxMin();
        double maxx = gridInfo.getxMax();
        double miny = gridInfo.getyMin();
        double maxy = gridInfo.getyMax();

        double gridx = (maxx-minx)/(cols-1);
        double gridy = (maxy-miny)/(rows-1);
        List<GridPointDto> gridPointDtos = new ArrayList<>();
        for (int i=0;i<rows;i++){
            for (int j=0;j<cols;j++){
                double val = fvals[i*rows+j];
                if ( val != -9999.0){
                    GridPointDto gridPointDto = new GridPointDto();
                    gridPointDto.setVal(val);
                    gridPointDto.setLon(minx+j*gridx);
                    gridPointDto.setLat(miny+i*gridy);
                    gridPointDtos.add(gridPointDto);
                }

            }
        }
        return SysResult.success(gridPointDtos);
//        GridDto gridDto = new GridDto(gridInfo,fvals);
//        return SysResult.success(gridDto,file.getPath());
    }

    @ApiOperation("保存文件")
    @PostMapping("/save")
    public SysResult save(String nTimes, MultipartFile data,String dateChar,String timeChar,String type) throws IOException {
        QxGridFile qxGridFile = new QxGridFile();
        qxGridFile.setNtimes(nTimes);
        qxGridFile.setData(data.getBytes());
        qxGridFile.setDatechar(dateChar);
        qxGridFile.setTimechar(timeChar);
        qxGridFile.setType(type);
        QxGridFile save = qxGridFileService.save(qxGridFile);
        return SysResult.success(save.get_id());
    }

    /**
     * 获取文件
     * @param suffix
     * @return
     */
    private File getFile(String suffix){
        String fileName = UUID.randomUUID()+"."+suffix;
        File file = new File(getFilePath(),fileName);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()){
            boolean mkdir = parentFile.mkdir();
            log.info(mkdir?"文件夹创建成功":"文件夹创建失败");
        }
        return file;
    }

    private String getFilePath(){
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        return applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\file";
    }

    private Boolean deleteFile(String filePath){
        File file = new File(filePath);
        return file.delete();
    }



}
